package main

import (
	"gitee.com/zxs-micro-2/zxs-micro-proto/demouser/user"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

var client user.DemoUserClient
var clientConn *grpc.ClientConn

func initClient() {
	conn, err := grpc.Dial("127.0.0.1:8124", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}
	clientConn = conn
	client = user.NewDemoUserClient(conn)
}

func main() {
	initClient()
	defer clientConn.Close()
	e := gin.New()
	ug := e.Group("/user")
	ug.POST("/user", func(ctx *gin.Context) {
		//登陆
		ls := new(LoginStruct)
		err := ctx.BindJSON(ls)
		if err != nil {
			ctx.JSON(500, err)
			return
		}
		rsp, err := client.UserLogin(ctx.Request.Context(), &user.UserLoginRequest{
			Account: ls.UserName, Pwd: ls.Password,
		})
		if err != nil {
			ctx.JSON(500, err)
		} else {
			ctx.JSON(200, rsp)
		}
	})
	ug.GET("/user/:token", func(ctx *gin.Context) {
		//获取信息
		tk := ctx.Param("token")
		if tk == "" {
			ctx.JSON(200, nil)
			return
		}
		rsp, err := client.UserInfo(ctx.Request.Context(), &user.UserInfoRequest{
			Token: tk,
		})
		if err != nil {
			ctx.JSON(500, err)
		} else {
			ctx.JSON(200, rsp)
		}
	})
	ug.PUT("/user", func(ctx *gin.Context) {
		//注册
		ls := new(RegisterStruct)
		err := ctx.BindJSON(ls)
		if err != nil {
			ctx.JSON(500, err)
			return
		}
		rsp, err := client.UserRegister(ctx.Request.Context(), &user.UserRegisterRequest{
			Account: ls.UserName, Pwd: ls.Password, VerifyPwd: ls.RepeatPassword, RegisterCode: ls.VerifyCode,
		})
		if err != nil {
			ctx.JSON(500, err)
		} else {
			ctx.JSON(200, rsp)
		}
	})
	e.Run(":8123")
}

type LoginStruct struct {
	UserName string `json:"user_name"`
	Password string `json:"password"`
}

type RegisterStruct struct {
	UserName       string `json:"user_name"`
	Password       string `json:"password"`
	RepeatPassword string `json:"repeat_password"`
	VerifyCode     string `json:"verify_code"`
}
